package com.yinxing.framework.convert;

import org.springframework.core.convert.converter.Converter;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

public class StringToLocalDateTimeConverter implements Converter<String, LocalDateTime> {

    private final static String shortPattern = "yyyy-MM-dd";
    private final static String middlePattern = "yyyy-MM-dd HH:mm";
    private final static String longPattern = "yyyy-MM-dd HH:mm:ss";

    @Override
    public LocalDateTime convert(String source) {
        if(StringUtils.hasText(source)) {
            try {
                return autoMatch(source);
            } catch (ParseException e) {
                throw new IllegalArgumentException("this date argument's format must be " +
                        "[yyyy-MM-dd , yyyy-MM-dd HH:mm , yyyy-MM-dd HH:mm:ss]");
            }
        }
        return null;
    }

    private LocalDateTime autoMatch(String strDate) throws ParseException {
        String format = null;
        switch (strDate.length()) {
            case 10:
                format = shortPattern;
                break;
            case 16:
                format = middlePattern;
                break;
            case 19:
                format = longPattern;
                break;
        }
        Date date = new SimpleDateFormat(format).parse(strDate);
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        return instant.atZone(zoneId).toLocalDateTime();
    }
}
